{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 随机梯度下降法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "m = 100000\n",
    "x = np.random.normal(size=m)\n",
    "y = x * 4. + 3. + np.random.normal(0., 3., size=m)\n",
    "X = x.reshape(-1, 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def J(X_b, y, theta):\n",
    "    try:\n",
    "        return np.sum((y - X_b.dot(theta)) ** 2) / len(X_b)\n",
    "    except:\n",
    "        return float('inf')\n",
    "    \n",
    "def dJ(X_b, y, theta):\n",
    "    return X_b.T.dot(X_b.dot(theta) - y) * 2. / len(X_b)\n",
    "\n",
    "def gradient_descent(X_b, y, initial_theta, eta=0.01, epsilon = 1e-8, n_iters = 1e4):\n",
    "    theta = initial_theta\n",
    "    cur_iter = 0\n",
    "    \n",
    "    while cur_iter < n_iters:\n",
    "        gradient = dJ(X_b, y,theta)\n",
    "        last_theta = theta\n",
    "        theta = theta - eta * gradient\n",
    "        \n",
    "        if abs(J(X_b, y, last_theta) - J(X_b, y, theta)) < epsilon:\n",
    "            break\n",
    "            \n",
    "        cur_iter += 1\n",
    "        \n",
    "    return theta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.02 s, sys: 49.3 ms, total: 1.07 s\n",
      "Wall time: 910 ms\n"
     ]
    }
   ],
   "source": [
    "X_b = np.hstack([np.ones((len(X), 1)), X])\n",
    "initial_theta = np.zeros(X_b.shape[1])\n",
    "\n",
    "%time theta = gradient_descent(X_b, y, initial_theta)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 2.99180475,  3.99530436])"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "theta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(100000,)"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(100000, 2)"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X_b.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def dJ_sgd(X_b_i, y_i, theta):\n",
    "    return X_b_i.T.dot(X_b_i.dot(theta) - y_i) * 2\n",
    "\n",
    "def sgd(X_b, y, initial_theta, epsilon = 1e-8, n_iters = 1e4):\n",
    "    theta = initial_theta\n",
    "    \n",
    "    t0 = 5\n",
    "    t1 = 50\n",
    "    \n",
    "    def learning_rate(t):\n",
    "        return t0 / (t + t1)\n",
    "    \n",
    "        \n",
    "    for cur_iter in range(n_iters):\n",
    "        rand = np.random.randint(len(X_b))\n",
    "        \n",
    "        gradient = dJ_sgd(X_b[rand], y[rand],theta)\n",
    "        last_theta = theta\n",
    "        theta = theta - learning_rate(cur_iter) * gradient\n",
    "        \n",
    "            \n",
    "        cur_iter += 1\n",
    "        \n",
    "    return theta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 292 ms, sys: 4.09 ms, total: 296 ms\n",
      "Wall time: 304 ms\n"
     ]
    }
   ],
   "source": [
    "%time theta = sgd(X_b, y, initial_theta, n_iters=len(X_b) // 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 2.97112126,  3.99218105])"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "theta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
